package net.xdclass.order_server.service.impl;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import net.xdclass.order_server.domain.ProductOrder;
import net.xdclass.order_server.service.ProductClient;
import net.xdclass.order_server.service.ProductOrderService;

@Service
public class ProductOrderServiceImpl implements ProductOrderService {

	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private LoadBalancerClient loadBalancerClient;
	
	@Autowired
	private ProductClient productClient;
	
	Gson GSON=new Gson();
	
	JsonParser jsonParser=new JsonParser();
	
	@Override
	public ProductOrder save(int userId, int productId) {
		// TODO Auto-generated method stub
		
		String subfix="/api/v1/product/find?id="+productId;
		String serverId="product-service";
		Map<String,Object> ret=restTemplate.getForObject("http://"+serverId+subfix, Map.class);
		System.out.println(ret);
		
		
		String res=productClient.findById(productId);
		
		JsonObject json=jsonParser.parse(res).getAsJsonObject();
		
		
		//ServiceInstance serviceInstance=loadBalancerClient.choose(serverId);
		//String url=String.format("http://%s:%s"+subfix, serviceInstance.getHost(),serviceInstance.getPort());
		//ret=restTemplate.getForObject(url, Map.class);
		ProductOrder productOrder=new ProductOrder();
		productOrder.setCreateTime(new Date());
		productOrder.setUserId(userId);
		productOrder.setTradeNo(UUID.randomUUID().toString());
		productOrder.setProductName(ret.get("name").toString());
		productOrder.setPrice(json.get("price").getAsInt());
		return productOrder;
	}

}
